import tinymce from 'tinymce/tinymce'
import store from '@/store'
import axios from '@/utils/request'
import { getStrData2Save } from '@/utils/save'
import { exportFile, getBaseUrl, sleep, checkDocInEdit } from '@/utils/helpers'
import { Loading, Message } from 'element-ui'
import { uniqWith } from 'lodash'

export function fetchData(docId) {
  const { docNo, id } = store.state.xmleditor.editorConfig
  // 如果是html预览页面，使用修改后的接口
  const baseUrl = getBaseUrl() + (store.getters.entry === 'htmlpreview' ? '/html' : '')
  return axios({ url: `${baseUrl}/${docId || docNo || id}` })
}

// 批量新增文档引用记录
function batchAddRefRecord(list = []) {
  const { docNo, id, editContentType } = store.state.xmleditor.editorConfig
  return axios({
    method: 'post',
    url: '/editor/documentReferenceRecord/batchAdd',
    data: {
      editContentNo: docNo || id,
      editContentType,
      list
    }
  })
}

function getRefRecordList() {
  const refdocSel = '#tinymce>.page-wrapper [data-type="refdoc"]'
  const refchapterSel = '#tinymce>.page-wrapper [data-type="refchapter"]'
  const refArr = tinymce.activeEditor.dom.select(`${refdocSel},${refchapterSel}`)
  return uniqWith(refArr, (a, b) => {
        const d1 = a.dataset
        const d2 = b.dataset
        return d1.refcode === d2.refcode && d1.refversion === d2.refversion
      })
    .map((node) => {
      const standardId = node.dataset.standardid
      return {
        standardId: standardId === 'undefined' || !standardId ? '' : standardId,
        mainContentId: node.dataset.maincontentid === 'null' ? null : node.dataset.maincontentid,
        standardNo: node.dataset.refcode,
        standardVersion: node.dataset.refversion,
        standardName: node.dataset.refname,
        refType: 'refdoc',
        category: node.dataset.category
      }
    })
}

/**
 * 向服务器提交并保存编辑器内容
 */
export function save(jsonContent, autoSave=false) {
  const { id, docNo, validToken } = store.state.xmleditor.editorConfig

  const data = { jsonContent }
  let url = getBaseUrl()
  if (store.getters.editContentType === 'document') {
    data.docNo = docNo
  } else {
    data.id = id
    url += '/content'
  }

  if (autoSave) {
    url += '/auto'
  }

  if (validToken) {
    data.validToken = validToken
  }

  return axios({ method: 'put', url, data }).then(() => batchAddRefRecord(getRefRecordList()))
}

export function removeCheck(contentId) {
  return axios({
    method: 'post',
    url: '/editor/documentInfo/chapter/remove/check',
    data: {
      docNo: store.state.xmleditor.editorConfig.docNo,
      contentId
    }
  })
}
export function addComment(data) {
  return axios({
    method: 'post',
    url: '/editor/documentCommentInfo',
    data
  })
}
export function fetchComments(keyword) {
  const { docNo } = store.state.xmleditor.editorConfig
  const docInEdit = checkDocInEdit()
  return axios({
    url: '/editor/documentCommentInfo/list',
    params: { docNo, keyword, docInEdit }
  }).then(({ data }) => {
    store.commit('xmleditor/SET_COMMENT_LIST', data)
  })
}

export function removeComment(id) {
  return axios({
    method: 'delete',
    url: '/editor/documentCommentInfo/' + id
  })
    .then(() => {
      tinymce.activeEditor.notificationManager.open({
        timeout: 1500,
        text: '删除成功!',
        type: 'success'
      })
    })
    .then(() => fetchComments())
}

export function updateComment({ id, content, startContainerId, endContainerId, docContent, startIndex, endIndex }) {
  return axios
    .put('/editor/documentCommentInfo', {
      id,
      content,
      docNo: store.state.xmleditor.editorConfig.docNo,
      startContainerId,
      endContainerId,
      docContent,
      startIndex,
      endIndex
    })
    .then(() => fetchComments())
    .then(() => {
      tinymce.activeEditor.notificationManager.open({
        timeout: 1500,
        text: '修改成功!',
        type: 'success'
      })
    })
}

export function addReply(data) {
  return axios({
    method: 'post',
    url: '/editor/documentCommentReplyInfo',
    data
  })
}

export function removeReply(id) {
  return axios({
    method: 'delete',
    url: '/editor/documentCommentReplyInfo/' + id
  })
    .then(() => {
      tinymce.activeEditor.notificationManager.open({
        timeout: 1500,
        text: '删除成功!',
        type: 'success'
      })
    })
    .then(() => fetchComments())
}

export function updateReply(data) {
  return axios
    .put('/editor/documentCommentReplyInfo', data)
    .then(() => fetchComments())
    .then(() => {
      tinymce.activeEditor.notificationManager.open({
        timeout: 1500,
        text: '修改成功!',
        type: 'success'
      })
    })
}

export function fetchHistory() {
  const standardNo = store.state.xmleditor.standardBaseInfo?.standardNo
  if (!standardNo) {
    throw new Error('标准编号不存在')
  }
  return axios({
    url: '/editor/documentInfo/history',
    params: { standardNo }
  }).then(({ data }) => {
    store.commit('xmleditor/SET_HISTORY_LIST', data)
  })
}

export function uploadFile(data) {
  return axios({
    method: 'post',
    url: '/editor/file/upload',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    data
  })
}

/** 文档对比 */
export function compare(data) {
  return axios({
    method: 'post',
    url: '/editor/documentInfo/compare',
    data
  })
}

/** 文档检查 */
export function docCheck(data) {
  return axios({
    method: 'post',
    url: '/editor/documentInfo/check',
    data
  })
}
/** 查询文档检查 */
export function getCheckList() {
  return axios({
    url: '/editor/documentCheckRecord/list',
    params: { docNo: store.state.xmleditor.editorConfig.docNo }
  }).then(({ data }) => {
    store.commit('xmleditor/SET_CHECK_RESULT', data)
  })
}

/** 导出检查报告 */
export function checkExport() {
  return axios({
    method: 'post',
    url: '/editor/documentInfo/check/export',
    responseType: 'blob',
    data: {
      docNo: store.state.xmleditor.editorConfig.docNo,
      content: getStrData2Save(),
      showRevisionLine: true
    }
  }).then(exportFile)
}
/** 收藏分类 */
export function getClassifyList() {
  return axios({
    url: '/editor/documentCollectClassify/list'
  }).then(({ data }) => {
    store.commit('xmleditor/SET_CLASSIFY_LIST', data)
  })
}

/** 收藏 */
export function addCollect(data) {
  return axios({
    method: 'post',
    url: '/editor/documentCollectInfo',
    data
  })
}

/** 查询文档协作列表 */
export function getCooperateList() {
  return axios({
    url: '/editor/documentCooperateInfo/list',
    params: { docNo: store.state.xmleditor.editorConfig.docNo }
  }).then(({ data }) => {
    store.commit('xmleditor/SET_COOPERATE_LIST', data)
  })
}

/** 获取组织架构一级列表 */
export function getFirstLevelOrgList() {
  return axios({
    method: 'post',
    url: '/editor/depend/org/getFirstLevelOrgList'
  }).then(({ data }) =>
    data.map((item) => {
      return {
        id: item.id,
        data: item,
        label: item.orgName,
        orgId: item.id,
        orgCode: item.orgCode,
        children: [],
        isLeaf: !item.hasChild
      }
    })
  )
}

/** 获取组织架构数据列表 */
export function qryOrgListByParentOrgId(data) {
  return axios({
    method: 'post',
    url: '/editor/depend/org/qryOrgListByParentOrgId',
    data
  }).then(({ data }) =>
    data.map((item) => {
      return {
        id: item.orgId,
        data: item,
        label: item.orgName,
        orgId: item.orgId,
        orgCode: item.orgCode,
        children: [],
        isOrgNode: true,
        isLeaf: item.isLeaf
      }
    })
  )
}

/** 获取组织架构下用户数据列表 */
export function qryEmployeeListByOrgId(data) {
  return axios({
    method: 'post',
    url: '/editor/depend/org/qryEmployeeListByOrgId',
    data
  }).then(({ data }) =>
    data.map((item) => {
      return {
        id: item.userId,
        data: item,
        label: item.userName,
        children: [],
        isUserNode: true,
        isLeaf: true
      }
    })
  )
}

/** 带搜索条件的获取组织架构下用户数据列表 */
export function selectOrgTreeByCondition(data, onlyOrg = false) {
  return axios({
    method: 'post',
    url: '/editor/depend/org/selectOrgTreeByCondition',
    data
  }).then(({ data }) => {
    const walk = (arr, isOrg = true) => {
      // children
      // 1. onlyOrg
      if (onlyOrg) {
        return arr.map((item) => {
          return {
            ...item,
            id: item.orgId,
            data: item,
            label: item.orgName,
            isLeaf: false,
            children: [...walk(item.children)]
          }
        })
      }
      // 2. org + userList
      if (isOrg) {
        return arr.map((item) => {
          return {
            ...item,
            id: item.orgId,
            data: item,
            label: item.orgName,
            isLeaf: false,
            children: [...walk(item.children), ...walk(item.userList, false)]
          }
        })
      }
      // userList
      return arr.map((item) => {
        return { ...item, label: item.userName, isLeaf: true, id: item.userId, data: item }
      })
    }
    return walk(data)
  })
}

/** 修改文档协作 */
export function modifyCollaborator(data) {
  return axios({
    method: 'put',
    url: '/editor/documentCooperateInfo',
    data
  })
    .then(() => Message.success('修改成功!'))
    .then(() => store.commit('xmleditor/SET_COLLABORATE_STATUS_CHANGE', true))
    .then(getCooperateList)
}

/** 完成文档协作 */
export function finishCollaborate(data) {
  return axios({
    method: 'post',
    url: '/editor/documentCooperateInfo/finish',
    data
  })
    .then(() => Message.success('修改成功!'))
    .then(() => store.commit('xmleditor/SET_COLLABORATE_STATUS_CHANGE', true))
    .then(getCooperateList)
}

/** 查询个人收藏分页 */
export function getCollectListApi(params) {
  return axios({
    url: '/editor/documentCollectInfo/page',
    params
  }).then(({ data }) => data)
}

/** 查询结构化内容块分页 */
export function getBlockListApi(params) {
  return axios({
    url: '/editor/documentBlockInfo/page',
    params
  }).then(({ data }) => data)
}

/** 查询术语库分页 */
export function getTermListApi(params) {
  return axios({
    url: '/editor/termsInfo/page',
    params
  }).then(({ data }) => data)
}

/** 查询缩略语库分页 */
export function getAbbrListApi(params) {
  return axios({
    url: '/editor/abbreviationInfo/page',
    params
  }).then(({ data }) => data)
}

/** 引用文件分页查询 */
export function getStandardPage(params) {
  return axios({
    url: '/editor/depend/standard/page',
    params
  }).then(({ data }) => data)
}

/** 引用文件查询JSON数据 */
export function getStandardContent(params) {
  return axios({
    url: '/editor/documentInfo/content/json',
    data: params,
    method: 'post'
  }).then(({ data }) => data)
}
/** 获取任务编号查询文档下载记录详细信息 */
async function getDownloadRecord(taskNo, callback) {
  const res = await axios('/editor/documentDownloadRecord/' + taskNo)
  if (res.data.taskStatus === 3) {
    callback && callback(res)
  } else if (res.data.taskStatus === 4) {
    Message.error('任务失败!')
  } else {
    Message.warning('任务处理中，请到下载中心查看!')
  }
}
/** 获取任务编号查询文档下载记录详细信息 */
export function getDownloadRecordList(fileName) {
  return axios('/editor/documentDownloadRecord/list', {
    params: { fileName, docNo: store.state.xmleditor.editorConfig.docNo }
  }).then(({ data }) => data)
}

/** 文档导出 */
export async function docExport(exportType = 'pdf') {
  const { data } = await axios({
    method: 'post',
    url: '/editor/documentInfo/export/async',
    data: {
      docNo: store.state.xmleditor.editorConfig.docNo,
      showRevisionLine: true,
      exportType
    }
  })
  const loadingInst = Loading.service()
  await sleep(5000)
  loadingInst.close()
  getDownloadRecord(data, (res) => {
    const url = window.location.origin + '/prod-api/editor/file/downloadByAttachment/' + res.data.filePath
    window.location.href = url
  })
}

/** 文档预览 */
export async function docPreview() {
  const { data } = await axios({
    method: 'post',
    url: '/editor/documentInfo/preview/async',
    data: {
      docNo: store.state.xmleditor.editorConfig.docNo,
      showRevisionLine: true
    }
  })
  const loadingInst = Loading.service()
  await sleep(5000)
  loadingInst.close()
  getDownloadRecord(data, (res) => {
    const open = window.open()
    open.location = window.location.origin + '/prod-api/editor/file/preview/' + res.data.filePath
  })
}

/** 文档删除 */
export async function docRemove(taskNo) {
  await axios({
    method: 'delete',
    url: '/editor/documentDownloadRecord/' + taskNo
  })
}

/** 修订线开关 */
export function revisionLineSwitch(showRevisionLine = false) {
  return axios({
    method: 'post',
    url: '/editor/documentInfo/revisionLineSwitch',
    data: {
      docNo: store.state.xmleditor.editorConfig.docNo,
      docContent: showRevisionLine ? getStrData2Save() : '',
      showRevisionLine
    }
  }).then(({ data }) => {
    store.commit('xmleditor/SET_REVISION_LINE_IDS', data?.contentIdList)
  })
}

// 获取术语JSON结构
export function getTermInfoJSON(id) {
  return axios(`/editor/termsInfo/json/${id}`).then(({ data }) => data)
}

// 获取缩略语JSON结构
export function getAbbrInfoJSON(id) {
  return axios(`/editor/abbreviationInfo/json/${id}`).then(({ data }) => data)
}

// 获取结构化内容块详细信息
export function getBlockInfoJSON(id) {
  return axios(`/editor/documentBlockInfo/${id}`).then(({ data }) => {
    try {
      return JSON.parse(data.jsonContent)?.filter((i) => i?.dataType !== 'blank_page')
    } catch (error) {
      return Promise.reject('错误的结构化数据')
    }
  })
}
// 获取标准规则下全量配置
export function getRuleInfoAll(ruleId) {
  return axios({
    url: '/editor/standardRuleInfo/all',
    params: { ruleId }
  }).then(({ data }) => {
    store.commit('xmleditor/SET_RULE_STRUCTURES', data?.structures)
    store.commit('xmleditor/SET_RULE_FONTS', data?.fonts)
    return data
  })
}
// 文件类型枚举值
export function getDependFileType() {
  return axios('/editor/depend/fileType').then(({ data }) => {
    store.commit('xmleditor/SET_DEPEND_FILETYPES', data)
    return data
  })
}
// 保存流程图的xml数据
export function saveFlowChartXml(data) {
  return axios({
    url: '/editor/documentInfo/flowChart',
    method: 'post',
    data
  }).then(({ data }) => {
    return data
  })
}
// 获取流程图的xml数据
export function getFlowChartXml(id) {
  return axios({
    url: '/editor/documentInfo/flowChart/' + id,
    method: 'get',
    params: {}
  }).then(({ data }) => {
    return data?.xmlContent
  })
}

// 通过OSSId 批量获取上传文件信息
export function getAttachmentByOssIds(params) {
  return axios({
    url: '/filenode/biz/service/cmos-doc-node/materials',
    method: 'post',
    data: params
  })
}

// 获取术语数据
export function getTermInfo(id) {
  return axios({
    url: '/editor/termsInfo/' + id,
    method: 'get'
  })
}
// 保存术语数据
export function saveTermContent(data, autoSave = false) {
  return axios({
    url: '/editor/termsInfo/content' + (autoSave ? '/auto' : ''),
    method: 'PUT',
    data
  })
}

/**
  getAttachmentByOssIds([fileId]).then(file => {
    if (file.success) {
      this.mainFile = file.data[0]
    } else {
      Message.error(file.errMessage || '获取附件失败')
    }
  })
 */
